package com.shkg.opencloud.fastdfs.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shkg.opencloud.common.bo.ApiResult;
import com.shkg.opencloud.common.bo.ApiResultUtil;
import com.shkg.opencloud.common.exception.BusinessException;
import com.shkg.opencloud.fastdfs.config.FileSystemConfig;
import com.shkg.opencloud.fastdfs.entity.UploadFile;
import com.shkg.opencloud.fastdfs.enums.MultipartfileStatusEnum;
import com.shkg.opencloud.fastdfs.util.FastDFSClient;
import com.shkg.opencloud.fastdfs.util.MD5Util;
import com.shkg.opencloud.idsc.servers.fileaccess.dto.UploadFileDTO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * <pre>
 *
 * </pre>
 *
 * @author: caipeng
 * @date: 2019/9/16
 * @time: 14:19
 * @version:
 */
@Service
public class AccessFileService {

    @Autowired
    private UploadFileService service;

    @Autowired
    private FileSystemConfig fileSystemConfig;

    @Autowired
    private FastDFSClient fastDFSClient;


    /**
     * 单次 上传保存 图片
     *
     * @param file
     * @param fk
     * @return
     */
    public UploadFileDTO uploadImage(MultipartFile file, String fk) {
        BufferedImage image;
        try {
            image = ImageIO.read(file.getInputStream());
        } catch (IOException e) {
            throw BusinessException.of(MultipartfileStatusEnum.F400);
        }
        String fileMD5;
        try {
            fileMD5 = MD5Util.md5HashCode32(file.getInputStream());
        } catch (Exception e) {
            throw BusinessException.of(MultipartfileStatusEnum.F200);
        }
        UploadFile fileInfo = checkByFilesMD5AndFK(fileMD5);
        UploadFileDTO dto;

        if (fileInfo != null) {
            // 文件已经存在

            File f;

            UploadFile newfileInfo = new UploadFile();
            //文件没有上传过
            newfileInfo.setFilesMD5(fileMD5);
            //文件名称
            newfileInfo.setFilesName(file.getOriginalFilename());
            //文件大小
            newfileInfo.setFileSize(file.getSize());
            //文件类型
            newfileInfo.setFilesType(file.getContentType());
            //服务器地址
            newfileInfo.setFilesPath(fileInfo.getFilesPath());
//            //文件访问的全路劲
//            newfileInfo.setFilesUrl(fileInfo.getFilesUrl());
            //文件上传时间   默认当前系统时间
            newfileInfo.setUploadTime(new Date());
            //外键
            newfileInfo.setForeignKey(fk);
            //删除标志   数据库默认为0
            newfileInfo.setDeleteFlag(0);
            //保存数据入库
            Boolean SaveFlag = service.save(newfileInfo);


            dto = UploadFileDTO.builder()
                    .id(newfileInfo.getId())
                    .deleteFlag(newfileInfo.getDeleteFlag())
                    .foreignKey(newfileInfo.getForeignKey())
                    .fileSize(newfileInfo.getFileSize())
                    .filesMD5(newfileInfo.getFilesMD5())
                    .filesName(newfileInfo.getFilesName())
                    .filesUrl(fileSystemConfig.getFileFullPath(newfileInfo.getFilesPath()))
                    .filesType(newfileInfo.getFilesType())
                    .build();
            return dto;
        } else {
            // 保存新文件
            String url;
            try {
                url = fastDFSClient.uploadImageWithThumbImage(file);
            } catch (IOException e) {
                throw BusinessException.of(MultipartfileStatusEnum.F600);
            }
            fileInfo = new UploadFile();
            //文件没有上传过
            fileInfo.setFilesMD5(fileMD5);
            //文件名称
            fileInfo.setFilesName(file.getOriginalFilename());
            //文件大小
            fileInfo.setFileSize(file.getSize());
            //文件类型
            fileInfo.setFilesType(file.getContentType());
            //服务器地址
            fileInfo.setFilesPath(url);
//            //拼接了IP加端口的路劲地址、
//            String picFullPath = fileSystemConfig.getFileFullPath(url);
//            //文件访问的全路劲
//            fileInfo.setFilesUrl(picFullPath);
            //文件上传时间   默认当前系统时间
            fileInfo.setUploadTime(new Date());
            //外键
            fileInfo.setForeignKey(fk);
            //删除标志   数据库默认为0
            fileInfo.setDeleteFlag(0);
            //保存数据入库
            Boolean SaveFlag = service.save(fileInfo);

            if (SaveFlag) {

                dto = UploadFileDTO.builder()
                        .id(fileInfo.getId())
                        .deleteFlag(fileInfo.getDeleteFlag())
                        .foreignKey(fileInfo.getForeignKey())
                        .fileSize(fileInfo.getFileSize())
                        .filesMD5(fileInfo.getFilesMD5())
                        .filesName(fileInfo.getFilesName())
//                        .filesUrl(fileInfo.getFilesUrl())
                        .filesUrl(fileSystemConfig.getFileFullPath(url))
                        .filesType(fileInfo.getFilesType())
                        .build();

            } else {
                throw BusinessException.of(MultipartfileStatusEnum.F700);
            }
        }

        return dto;
    }


    /**
     * 单次 上传保存 文件
     *
     * @param file
     * @param fk
     * @return
     */
    public UploadFileDTO uploadFile(MultipartFile file, String fk) {
        String fileMD5;
        try {
            fileMD5 = MD5Util.md5HashCode32(file.getInputStream());
        } catch (Exception e) {
            throw BusinessException.of(MultipartfileStatusEnum.F200);
        }
        UploadFile fileInfo = checkByFilesMD5AndFK(fileMD5);
        UploadFileDTO dto;

        if (fileInfo != null) {
            // 文件已经存在

            UploadFile newfileInfo = new UploadFile();
            //文件没有上传过
            newfileInfo.setFilesMD5(fileMD5);
            //文件名称
            newfileInfo.setFilesName(file.getOriginalFilename());
            //文件大小
            newfileInfo.setFileSize(file.getSize());
            //文件类型
            newfileInfo.setFilesType(file.getContentType());
            //服务器地址
            newfileInfo.setFilesPath(fileInfo.getFilesPath());
//            //文件访问的全路劲
//            newfileInfo.setFilesUrl(fileInfo.getFilesUrl());
            //文件上传时间   默认当前系统时间
            newfileInfo.setUploadTime(new Date());
            //外键
            newfileInfo.setForeignKey(fk);
            //删除标志   数据库默认为0
            newfileInfo.setDeleteFlag(0);
            //保存数据入库
            Boolean SaveFlag = service.save(newfileInfo);

            dto = UploadFileDTO.builder()
                    .id(newfileInfo.getId())
                    .deleteFlag(newfileInfo.getDeleteFlag())
                    .foreignKey(newfileInfo.getForeignKey())
                    .fileSize(newfileInfo.getFileSize())
                    .filesMD5(newfileInfo.getFilesMD5())
                    .filesName(newfileInfo.getFilesName())
//                    .filesUrl(newfileInfo.getFilesUrl())
                    .filesUrl(fileSystemConfig.getFileFullPath(newfileInfo.getFilesPath()))
                    .filesType(newfileInfo.getFilesType())
                    .build();
            return dto;
        } else {
            // 保存新文件
            String url;
            try {
                url = fastDFSClient.uploadFile(file);
            } catch (IOException e) {
                throw BusinessException.of(MultipartfileStatusEnum.F600);
            }
            fileInfo = new UploadFile();
            //文件没有上传过
            fileInfo.setFilesMD5(fileMD5);
            //文件名称
            fileInfo.setFilesName(file.getName());
            //文件大小
            fileInfo.setFileSize(file.getSize());
            //文件类型
            fileInfo.setFilesType(file.getContentType());
            //服务器地址
            fileInfo.setFilesPath(url);
            //拼接了IP加端口的路劲地址、
            String picFullPath = fileSystemConfig.getFileFullPath(url);
            //文件访问的全路劲
//            fileInfo.setFilesUrl(picFullPath);
            //文件上传时间   默认当前系统时间
            fileInfo.setUploadTime(new Date());
            //外键
            fileInfo.setForeignKey(fk);
            //删除标志   数据库默认为0
            fileInfo.setDeleteFlag(0);
            //保存数据入库
            Boolean SaveFlag = service.save(fileInfo);

            if (SaveFlag) {

                dto = UploadFileDTO.builder()
                        .id(fileInfo.getId())
                        .deleteFlag(fileInfo.getDeleteFlag())
                        .foreignKey(fileInfo.getForeignKey())
                        .fileSize(fileInfo.getFileSize())
                        .filesMD5(fileInfo.getFilesMD5())
                        .filesName(fileInfo.getFilesName())
//                        .filesUrl(fileInfo.getFilesUrl())
                        .filesUrl(fileSystemConfig.getFileFullPath(url))
                        .filesType(fileInfo.getFilesType())
                        .build();

            } else {
                throw BusinessException.of(MultipartfileStatusEnum.F700);
            }
        }

        return dto;
    }

    /**
     * 批量 上传保存 图片
     *
     * @param files
     * @param fk
     * @return
     */
    public Map<String, UploadFileDTO> batUploadImage(MultipartFile[] files, String fk) {

        Map<String, UploadFileDTO> rst = new HashMap<>();

        Map<String, Integer> md5Map = new HashMap<>();
        Map<String, Integer> hadMap = new HashMap<>();
        Map<Integer, String> rstMap = new HashMap<>();
        for (int i = 0; i < files.length; i++) {
            String fileMD5 = null;
            try {
                fileMD5 = MD5Util.md5HashCode32(files[i].getInputStream());
            } catch (IOException e) {
                rstMap.put(i, "文件读取异常");
                continue;
            }

            Integer count = countByFilesMD5(fileMD5);
            if (count > 0) {
                hadMap.put(fileMD5, i);
                rstMap.put(i, "文件已存在");
            } else {
                md5Map.put(fileMD5, i);
            }
        }

        if (!md5Map.isEmpty() && md5Map.size() > 0) {

            md5Map.forEach((k, v) -> {
                MultipartFile file = files[v];


                BufferedImage image;
                try {
                    image = ImageIO.read(file.getInputStream());
                } catch (IOException e) {
                    rstMap.put(v, "图片文件解析失败");
                    return;
                }
                String fileMD5;
                try {
                    fileMD5 = MD5Util.md5HashCode32(file.getInputStream());
                } catch (Exception e) {
                    rstMap.put(v, "无法读取文件流");
                    return;
                }
                UploadFile fileInfo = checkByFilesMD5AndFK(fileMD5);
                UploadFileDTO dto;

                if (fileInfo != null) {
                    // 文件已经存在
                    dto = UploadFileDTO.builder()
                            .id(fileInfo.getId())
                            .deleteFlag(fileInfo.getDeleteFlag())
                            .foreignKey(fileInfo.getForeignKey())
                            .fileSize(fileInfo.getFileSize())
                            .filesMD5(fileInfo.getFilesMD5())
                            .filesName(fileInfo.getFilesName())
//                            .filesUrl(fileInfo.getFilesUrl())
                            .filesUrl(fileSystemConfig.getFileFullPath(fileInfo.getFilesPath()))
                            .filesType(fileInfo.getFilesType())
                            .build();
                    rst.put(dto.getFilesName(), dto);
                    return;
                } else {
                    // 保存新文件
                    String url;
                    try {
                        url = fastDFSClient.uploadImageWithThumbImage(file);
                    } catch (IOException e) {
                        rstMap.put(v, "文件保存失败");
                        return;
                    }

                    //文件没有上传过
                    fileInfo.setFilesMD5(fileMD5);
                    //文件名称
                    fileInfo.setFilesName(file.getOriginalFilename());
                    //文件大小
                    fileInfo.setFileSize(file.getSize());
                    //文件类型
                    fileInfo.setFilesType(file.getContentType());
                    //服务器地址
                    fileInfo.setFilesPath(url);
                    //拼接了IP加端口的路劲地址、
//                    String picFullPath = fileSystemConfig.getFileFullPath(url);
                    String picFullPath = url;
//                    //文件访问的全路劲
//                    fileInfo.setFilesUrl(picFullPath);
                    //文件上传时间   默认当前系统时间
                    fileInfo.setUploadTime(new Date());
                    //外键
                    fileInfo.setForeignKey(fk);
                    //删除标志   数据库默认为0
                    fileInfo.setDeleteFlag(0);
                    //保存数据入库
                    Boolean SaveFlag = service.save(fileInfo);

                    if (SaveFlag) {

                        dto = UploadFileDTO.builder()
                                .id(fileInfo.getId())
                                .deleteFlag(fileInfo.getDeleteFlag())
                                .foreignKey(fileInfo.getForeignKey())
                                .fileSize(fileInfo.getFileSize())
                                .filesMD5(fileInfo.getFilesMD5())
                                .filesName(fileInfo.getFilesName())
//                                .filesUrl(fileInfo.getFilesUrl())
                                .filesUrl(fileSystemConfig.getFileFullPath(fileInfo.getFilesPath()))
                                .filesType(fileInfo.getFilesType())
                                .build();

                    } else {
                        rstMap.put(v, "文件信息保存失败");
                        return;
                    }
                    rst.put(dto.getFilesName(), dto);
                    return;
                }
            });
        }

        rstMap.forEach((k, v) -> {
            rst.put(files[k].getOriginalFilename(), UploadFileDTO.builder().filesUrl(v).build());
        });

        return rst;
    }


    public Map<String, UploadFileDTO> uploadImageOne2One(MultipartFile[] files, String fks) {
        Map<String, UploadFileDTO> rst = new HashMap<>();

        int countFile = files.length;

        List<String> cids_2 = new ArrayList<>();

        if (fks.contains(",")) {
            String[] cids_ = fks.split(",");
            for (int j = 0; j < cids_.length; j++) {
                cids_2.add(cids_[j].trim());
            }
        } else {
            throw BusinessException.of(MultipartfileStatusEnum.F900);
        }

        int countFK = cids_2.size();

        if (countFile != countFK) {
            throw BusinessException.of(MultipartfileStatusEnum.F900);
        }


        for (int i = 0; i < countFile; i++) {
            try {
                UploadFileDTO dto = uploadImage(files[i], cids_2.get(i));
                rst.put(cids_2.get(i), dto);
            } catch (Exception e) {
                rst.put(cids_2.get(i), UploadFileDTO.builder().filesUrl(files[i].getOriginalFilename() + "文件保存失败").build());
            }
        }

        return rst;
    }


    /**
     * 批量 上传保存 文件
     *
     * @param files
     * @param fk
     * @return
     */
    public Map<String, UploadFileDTO> batUploadFile(MultipartFile[] files, String fk) {


        Map<String, UploadFileDTO> rst = new HashMap<>();

        Map<String, Integer> md5Map = new HashMap<>();
        Map<String, Integer> hadMap = new HashMap<>();
        Map<Integer, String> rstMap = new HashMap<>();
        for (int i = 0; i < files.length; i++) {
            String fileMD5 = null;
            try {
                fileMD5 = MD5Util.md5HashCode32(files[i].getInputStream());
            } catch (IOException e) {
                rstMap.put(i, "文件读取异常");
                continue;
            }
            Integer count = countByFilesMD5(fileMD5);
            if (count > 0) {
                hadMap.put(fileMD5, i);
                rstMap.put(i, "文件已存在");
            } else {
                md5Map.put(fileMD5, i);
            }
        }
        if (!md5Map.isEmpty() && md5Map.size() > 0) {

            md5Map.forEach((k, v) -> {
                MultipartFile file = files[v];
                String fileMD5;
                try {
                    fileMD5 = MD5Util.md5HashCode32(file.getInputStream());
                } catch (Exception e) {
                    rstMap.put(v, "无法读取文件流");
                    return;
                }
                UploadFile fileInfo = checkByFilesMD5AndFK(fileMD5);
                UploadFileDTO dto;

                if (fileInfo != null) {
                    // 文件已经存在
                    dto = UploadFileDTO.builder()
                            .id(fileInfo.getId())
                            .deleteFlag(fileInfo.getDeleteFlag())
                            .foreignKey(fileInfo.getForeignKey())
                            .fileSize(fileInfo.getFileSize())
                            .filesMD5(fileInfo.getFilesMD5())
                            .filesName(fileInfo.getFilesName())
//                            .filesUrl(fileInfo.getFilesUrl())
                            .filesUrl(fileSystemConfig.getFileFullPath(fileInfo.getFilesPath()))
                            .filesType(fileInfo.getFilesType())
                            .build();
                    rst.put(dto.getFilesName(), dto);
                    return;
                } else {
                    // 保存新文件
                    String url;
                    try {
                        url = fastDFSClient.uploadFile(file);
                    } catch (IOException e) {
                        rstMap.put(v, "文件保存失败");
                        return;
                    }
                    fileInfo = new UploadFile();
                    //文件没有上传过
                    fileInfo.setFilesMD5(fileMD5);
                    //文件名称
                    fileInfo.setFilesName(file.getOriginalFilename());
                    //文件大小
                    fileInfo.setFileSize(file.getSize());
                    //文件类型
                    fileInfo.setFilesType(file.getContentType());
                    //服务器地址
                    fileInfo.setFilesPath(url);
                    //拼接了IP加端口的路劲地址、
                    String picFullPath = fileSystemConfig.getFileFullPath(url);
                    //文件访问的全路劲
//                    fileInfo.setFilesUrl(picFullPath);
                    //文件上传时间   默认当前系统时间
                    fileInfo.setUploadTime(new Date());
                    //外键
                    fileInfo.setForeignKey(fk);
                    //删除标志   数据库默认为0
                    fileInfo.setDeleteFlag(0);
                    //保存数据入库
                    Boolean SaveFlag = service.save(fileInfo);

                    if (SaveFlag) {

                        dto = UploadFileDTO.builder()
                                .id(fileInfo.getId())
                                .deleteFlag(fileInfo.getDeleteFlag())
                                .foreignKey(fileInfo.getForeignKey())
                                .fileSize(fileInfo.getFileSize())
                                .filesMD5(fileInfo.getFilesMD5())
                                .filesName(fileInfo.getFilesName())
//                                .filesUrl(fileInfo.getFilesUrl())
                                .filesUrl(fileSystemConfig.getFileFullPath(fileInfo.getFilesPath()))
                                .filesType(fileInfo.getFilesType())
                                .build();

                    } else {
                        rstMap.put(v, "文件信息保存失败");
                        return;
                    }
                    rst.put(dto.getFilesName(), dto);
                    return;
                }
            });
        }

        rstMap.forEach((k, v) -> {
            rst.put(files[k].getOriginalFilename(), UploadFileDTO.builder().filesUrl(v).build());
        });

        return rst;
    }


    /**
     * 获取指定文件 -- 使用业务外键和文件md5
     *
     * @param fk
     * @param md5
     * @return
     */
    public UploadFile getFileByMd5(String fk, String md5) {

        //根据MD5返回对应的uploadFile对象
        UploadFile uploadFile = service.getOne(new QueryWrapper<UploadFile>().eq("foreign_key", fk).eq("files_md5", md5).eq("delete_flag", 0L).last("LIMIT 1"));
        return uploadFile;
    }


    /**
     * 获取文件列表 -- 使用业务外键
     *
     * @param fk
     * @return
     */
    public List<UploadFileDTO> getFileByFk(String fk) {
        List<UploadFile> fileList = service.list(new QueryWrapper<UploadFile>().eq("foreign_key", fk).eq("delete_flag", 0L));

        List<UploadFileDTO> dtoList = new ArrayList<UploadFileDTO>();
        fileList.forEach(i -> {
            UploadFileDTO dto = UploadFileDTO.builder()
                    .id(i.getId())
                    .deleteFlag(i.getDeleteFlag())
                    .fileSize(i.getFileSize())
                    .filesMD5(i.getFilesMD5())
                    .filesName(i.getFilesName())
                    .filesPath(i.getFilesPath())
                    .filesType(i.getFilesType())
//                    .filesUrl(i.getFilesUrl())
                    .filesUrl(fileSystemConfig.getFileFullPath(i.getFilesPath()))
                    .foreignKey(i.getForeignKey())
                    .build();
            dtoList.add(dto);
        });
        return dtoList;
    }

    /**
     * 获取业务外键最后文件 -- 使用业务主键
     *
     * @param fk
     * @return
     */
    public String getLastFileByFk(String fk) {
        String filesUrl = null;
        LambdaQueryWrapper<UploadFile> queryWrapper = Wrappers.<UploadFile>lambdaQuery().orderByDesc(UploadFile::getUploadTime);
        queryWrapper.eq(UploadFile::getForeignKey, fk).eq(UploadFile::getDeleteFlag, 0L).last("LIMIT 1");
        List<UploadFile> uploadFileList = service.list(queryWrapper);
        //这里的filesPath需要是这种格式的：group1/M00/00/00/wKg7g1wN2YyAAH1MAADJbaKmScw004.jpg
        if (uploadFileList.size() > 0) {
            for (UploadFile uploadFile : uploadFileList) {
//                filesUrl = uploadFile.getFilesUrl();
                filesUrl = fileSystemConfig.getFileFullPath(uploadFile.getFilesPath());
            }
        }
        return filesUrl;
    }

    /**
     * 获取业务外键最后的文件 -- 使用业务主键
     *
     * @param fk
     * @return
     */
    public Map<String, String> getLastFilesByFks(List<String> fk) {
        Map<String, String> rst = new HashMap<String, String>();
        //根据MD5返回对应的uploadFile对象
        List<UploadFile> uploadFileList = service.list(new QueryWrapper<UploadFile>().in("foreign_key", fk).eq("delete_flag", 0));
        //这里的filesPath需要是这种格式的：group1/M00/00/00/wKg7g1wN2YyAAH1MAADJbaKmScw004.jpg
        if (uploadFileList.size() > 0) {
            for (UploadFile uploadFile : uploadFileList) {
                rst.put(uploadFile.getForeignKey(), fileSystemConfig.getFileFullPath(uploadFile.getFilesPath()));
            }
        }
        return rst;
    }


    /**
     * 删除指定文件 -- 使用业务外键和文件md5
     *
     * @param fk
     * @param md5
     * @return
     */
    public ApiResult delFileByMd5(String fk, String md5) {
        Boolean opt;
        //考虑双同步的问题，先删数据库在删服务器的文件(需要文件在服务器保存的地址)
        //1.先根据filesMD5和cid找到对应的UploadFile对象
        int count = countByFilesMD5(md5);
        if (count > 1) {
            UploadFile uploadFile = service.getOne(new QueryWrapper<UploadFile>().eq("foreign_key", fk).eq("files_md5", md5).eq("delete_flag", 0).last("LIMIT 1"));
            if (uploadFile != null && StringUtils.isNotEmpty(uploadFile.getFilesPath())) {
                opt = service.removeById(uploadFile.getId());
                return ApiResultUtil.ok(opt);
            } else {
                return ApiResultUtil.failure("数据不存在，无法删除");
            }
        } else if (count == 1) {
            UploadFile uploadFile = service.getOne(new QueryWrapper<UploadFile>().eq("foreign_key", fk).eq("files_md5", md5).eq("delete_flag", 0).last("LIMIT 1"));
            if (uploadFile != null && StringUtils.isNotEmpty(uploadFile.getFilesPath())) {
                opt = service.removeById(uploadFile.getId());
                if (opt) {
                    //3.数据库修改成功，删除服务器对应的文件(fileUrl 文件地址：以group开头)
                    fastDFSClient.deleteFile( fileSystemConfig.getFileFullPath(uploadFile.getFilesPath()) );
                    return ApiResultUtil.ok(opt);
                } else {
                    return ApiResultUtil.failure("数据删除失败，无法删除");
                }
            } else {
                return ApiResultUtil.failure("数据不存在，无法删除");
            }
        } else {
            return ApiResultUtil.ok(true);
        }
    }


    /**
     * 删除指定文件 -- 使用业务外键和文件md5
     *
     * @param fk
     * @return
     */
    public ApiResult delFileByFK(String fk) {
        Boolean opt;
        //考虑双同步的问题，先删数据库在删服务器的文件(需要文件在服务器保存的地址)
        //1.先根据filesMD5和cid找到对应的UploadFile对象

        List<UploadFile> recList = service.list(new QueryWrapper<UploadFile>().eq("foreign_key", fk).eq("delete_flag", 0));

        if (recList.size() > 0) {
            recList.forEach(i -> {
                delFileByMd5(i.getForeignKey(), i.getFilesMD5());
            });

        }
        int count = countByFK(fk);
        if (count > 0) {
            return ApiResultUtil.failure("未完全删除,操作失败");
        } else {
            return ApiResultUtil.ok(true);
        }
    }


    /**
     * @param filesMD5 ,cid
     * @return 返回boolean
     * 校验文件是否已经上传    true已经上传   false未上传或者异常
     */
    private UploadFile checkByFilesMD5AndFK(String filesMD5) {
//        UploadFile file = service.getOne(new QueryWrapper<UploadFile>().eq("foreign_key", cid).eq("files_md5", filesMD5).eq("delete_flag", 0).last("LIMIT 1"));
        UploadFile file = service.getOne(new QueryWrapper<UploadFile>().eq("files_md5", filesMD5).eq("delete_flag", 0).last("LIMIT 1"));

        return file;
    }


    /**
     * @param filesMD5 ,cid
     * @return 返回boolean
     * 校验文件是否已经上传    true已经上传   false未上传或者异常
     */
    private Integer countByFilesMD5(String filesMD5) {
        Integer count = service.count(new QueryWrapper<UploadFile>().eq("files_md5", filesMD5).eq("delete_flag", 0));
        if (count != null && count.intValue() > 0) {
            return count;
        }
        return 0;
    }


    /**
     * @param fk
     * @return 返回boolean
     * 校验文件是否已经上传    true已经上传   false未上传或者异常
     */
    private Integer countByFK(String fk) {
        Integer count = service.count(new QueryWrapper<UploadFile>().eq("foreign_key", fk).eq("delete_flag", 0));
        if (count != null && count.intValue() > 0) {
            return count;
        }
        return 0;
    }


    public byte[] download(String fileUrl) {
        return fastDFSClient.download(fileUrl);
    }

}
